/*
 * $Id: $
 */
package org.rcgwt.client.ui.grid.controller;

import org.rcgwt.client.ui.grid.internal.model.IHeaderModel;
import org.rcgwt.client.ui.grid.internal.model.IViewModel;
import org.rcgwt.client.ui.grid.internal.model.IViewModelElements;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Event;

/**
 * 
 * @author Olivier Oeuillot (latest modification by $Author: $)
 * @version $Revision: $ $Date: $
 */
public class DefaultViewController implements IViewController {

    public static final IViewController SINGLETON = new DefaultViewController();

    @Override
    public void onScrollEvent(IViewModel viewModel, Element viewElement,
            Event event) {

        IViewModelElements viewModelElements = viewModel.getViewModelElements();

        Element scrollableTableContainer = viewModelElements
                .getScrollableTableContainer();
        if (scrollableTableContainer == null) {
            return;
        }

        int scrollLeft = scrollableTableContainer.getScrollLeft();
        int scrollTop = scrollableTableContainer.getScrollTop();

        if (viewModel.setScrollPositions(scrollLeft, scrollTop) == false) {
            return;
        }

        for (IHeaderModel headerModel : viewModel.listHeaderModels()) {

            IHeaderModel.Orientation orientation = headerModel.getOrientation();

            int newScrollPosition;

            if (orientation == IHeaderModel.Orientation.HORIZONTAL) {
                newScrollPosition = scrollLeft;

            } else {
                newScrollPosition = scrollTop;
            }

            Element headerElement = viewModelElements
                    .getHeaderElement(headerModel);
            if (headerElement != null) {
                updateHeaderScrollPosition(headerElement, scrollLeft, scrollTop);
            }

            headerModel.setScrollPosition(newScrollPosition);
        }

    }

    protected void updateHeaderScrollPosition(Element headerElement,
            int scrollLeft, int scrollTop) {

        headerElement.setScrollLeft(scrollLeft);
        headerElement.setScrollTop(scrollTop);
    }
}
